package com.bw.controller;


import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.JwtUtils;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class LoginController {


    @Autowired
    UserMapper userMapper;

    @RequestMapping("/loginPage.do")
    public String loginPage() {

        return "login";
    }

    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult bindingResult, Model model, HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("error", bindingResult.getAllErrors().get(0).getDefaultMessage());

            return "login";

        }

        // 用户名是否存在
        User userDB = userMapper.selectByName(loginUser.getName());

        if (userDB == null) {
            model.addAttribute("error", "用户名不存在");
            return "login";
        }

        // 判断密码，处理一下 用户输入的密码

        String salt = userDB.getSalt(); // 数据库里的盐
        String password = userDB.getPassword();//  数据库的密码
        String loginUserPassword = loginUser.getPassword(); // 用户输入的密码

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt); // 加密用户输入的密码 + 数据库的盐

        if (!md5String.equals(password)) {
            model.addAttribute("error", "密码错误");
            return "login";
        }

        // 加密用户信息  得到token, 把token放入cookie， 设置cookie过期时间为30min, 把cookie返回给浏览器
        TokenUtils.responseTokenByCookie(userDB,response,30);
//        String token = JwtUtils.createToken(userDB,30);
//
//        Cookie cookie = new Cookie("token", token);
//        cookie.setMaxAge(60 * 30);
//        response.addCookie(cookie);


        return "redirect:list.do"; // 不是页面，   告诉浏览器  去访问http://localhost:8080/list.do
    }
}
